#!/usr/bin/perl -w

BEGIN {
	if(exists($::ENV{TRUECL_LIBS})) { push @INC,$::ENV{TRUECL_LIBS}; }
	if(exists($::ENV{TRUECL_CODE})) { push @INC,"$::ENV{TRUECL_CODE}/lib"; }
}

use cldb;
use strict;
use Getopt::Long;
use File::Basename;
use Data::Dumper;

$::_PRG=basename($0);

sub usage {
	print STDERR "
Usage: $::_PRG [--dbfile D] --query Y

";
	exit(1);
}

$::ARG_dbfile="$::ENV{TRUECL_CFG}/config.db";
if(!GetOptions(
	"dbfile=s"	=> \$::ARG_dbfile,
	"query=s"	=> \$::ARG_query
)) {
	usage;
}

if(!defined($::ARG_query)) { usage; }

if(! -f $::ARG_dbfile) {
	print STDERR "Error: Specified database file does not exist!\n";
	exit 1;
}

$::DBH = cldb->new($::ARG_dbfile);
if(!defined($::DBH)) {
	($::rc,$::str)=cldb->error;
	print STDERR "Error: $::str [rc=$::rc]\n";
	exit 1;
}

$::cmd=$::ARG_query;

if($::cmd !~ /^\s*select\s+/i) {
	my $r=$::DBH->do($::cmd);
	if(!$r) {
		($::rc,$::str)=cldb->error;
		print "Error attempting to perform SQL:\n$::str [$::rc]\n";
	}
	exit;
}

$::aref=$::DBH->get_rows($::cmd);
$::cc=0;
if(!defined($::aref)) {
	($::cc,$::rc)=$::DBH->error;
	print "Error attempting to list table\n$::rc\n";
	exit 1;
}

@::R=@$::aref;
exit if (!@::R);

#########################################################################
# Default column widths to display determined by the name of column.	#
#########################################################################

@::widths=();
$::i=0;
for $::ckey (keys(%{$::R[0]})) {
	$::widths[$::i]=length($::ckey);
	$::i++;
}

#########################################################################
# Widen the column widths to cope with data if necessary.		#
#########################################################################
for $::aa (@::R) {
	$::i=0;
	for $::ckey (keys(%$::aa)) {
		$::l=0;
		$::l=length($::aa->{$::ckey}) if defined($::aa->{$::ckey});
		$::widths[$::i]=0 if !defined($::widths[$::i]);
		$::widths[$::i]=$::l if $::l > $::widths[$::i];
		$::i++;
	}
}

$::i=0;
$::r="";
for $::ckey (keys(%{$::R[0]})) {
	$::r.=sprintf("%-*s  ",$::widths[$::i],$::ckey);
	$::i++;
}
print "$::r\n";

$::i=0; $::r="";
for $::ckey (keys(%{$::R[0]})) {
	$::r.="=" x $::widths[$::i];
	$::r.="  ";
	$::i++;
}
print "$::r\n";

#########################################################################
# Now dump out all records.						#
#########################################################################

for $::aa (@::R) {
	$::i=0;
	$::r="";
	for $::ckey (keys(%$::aa)) {
		if(defined($::aa->{$::ckey})) {
			$::r.=sprintf("%-*s  ",$::widths[$::i],$::aa->{$::ckey});
		} else {
			$::r.="  "." " x $::widths[$::i];
		}
		$::i++;
	}
	print "$::r\n";
}
print "\n";
print scalar(@::R)." Record" . (scalar(@::R)==1 ? "" : "s") . " found.\n";
exit 0;
